<?php
/**
 * 后台store管理员登录中间件
 *
 * Author: Zeon
 * Date: 2017/11/20
 * Created by Panxsoft.
 */
namespace App\Http\Middleware;

use App\Exceptions\ApiException;
use App\Exceptions\ApiErrCode;
use App\Models\Admin\StoreAdmin;
use App\Models\Store\Store;
use App\Services\Utils\ApiChecker;
use App\Services\Locale\Language;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\JWTGuard;

class StoreAuth {

    use ApiChecker;

    /**
     * @var Store
     */
    public static $store;

    /**
     * @var StoreAdmin
     */
    public static $store_admin;

    /**
     *
     * @example composer require tymon/jwt-auth@1.0.0-beta.3
     * @link http://jwt-auth.readthedocs.io/en/docs/quick-start/
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     * @throws \Exception
     */
    public function handle(Request $request, Closure $next)
    {
        $this->checkToken($request);

        /** @var JWTGuard $jwt */
        $jwt = Auth::guard('store');

        /** @var StoreAdmin|null $admin */
        $admin = $jwt->user(); // ?: PanxAdmin::mock();
        if (! $admin) {
            throw new ApiException(ApiErrCode::JWT_TOKEN_INVALID, trans('middleware.token_invalid'));
        }

        // check customer / store enabled
        $this->checkAdminStatus($admin);

        // 设置语言信息
        Language::setAppLocale($admin->language);

        self::$store_admin = $admin;

        self::$store = $admin->store;

        $this->debugShowStore($request);

        return $next($request);
    }

    /**
     * @param Request $request
     *
     * @throws ApiException
     */
    private function checkToken(Request $request)
    {
        if (config('app.debug_admin')) return;

        $this->checkJwtTokenExist($request,trans('checker.check_jwt_token_exist'));
    }

    /**
     * @param Request $req
     */
    private function debugShowStore(Request $req)
    {
        if ($req->exists('dd_store')) {
            dd(self::$store);
        }
    }

    /**
     * @param $admin
     * @throws \Exception
     */
    private function checkAdminStatus(StoreAdmin $admin): void
    {
        $this->checkUnless(
            $admin->is_deleted,
            trans('middleware.account_disabled')
        );

        $this->checkUnless(
            $admin->store->is_deleted,
            trans('middleware.store_admin.store_disabled')
        );

        $this->checkUnless(
            $admin->store->customer->is_deleted,
            trans('middleware.customer_admin.customer_disabled')
        );

        $this->checkIsTrue(
            $admin->store->customer->isProviderTypeNormal(),
            trans('middleware.customer_admin.customer_type_should_be_normal')
        );
    }
}